#include "wuziqiServer.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <json-c/json.h>
#include "stdShared.h"
#include <jsoncpp/json/json.h>
#include "stdSqliteDataBase.h"
#include <fstream>
#include "base64.h"
using namespace std;
#include<map>
#include<queue>
// extern std::map<int,int> m_map;
// extern std::queue<int> m_queue;

#define BUFFER_SIZE 128

int read_line(int fd, void *ptr, int max_len)
{
    char *buffer = (char *)ptr;
    char temp;
    int n_r;
    int i = 0;
    for (i = 0; i < max_len; i++)
    {
        n_r = read(fd, &temp, 1);

        if (n_r == 0)
        {
            if (i == 0)
            {
                return 0;
            }
            return i;
        }

        if (temp == '\n')
        {
            buffer[i] = temp;
            buffer[i + 1] = '\0';
            return i + 1;
        }
        else
        {
            buffer[i] = temp;
        }
    }
    if (n_r < 0)
    {
        perror("read error!");
        exit(1);
    }
    buffer[i] = '\n';
    buffer[i + 1] = '\0';
    return i + 1;
}

WUziqiServer::WUziqiServer(const std::shared_ptr<StdTcpSocket> &clientSock) : m_clientSock(clientSock)
{
    db = new StdSqliteBase;
}

void WUziqiServer::handleRegisterInfo(const std::string &info)
{
    json_object *jsonObj_1 = json_tokener_parse(info.c_str());
    // std::cout << info << std::endl;
    if (jsonObj_1 == NULL)
    {
        std::cout << "解析失败" << std::endl;
        return;
    }
    std::cout << info << std::endl;
    /* json字符串解析成功 */
    int type_1 = json_object_get_int(json_object_object_get(jsonObj_1, "type"));
    const char *username_1 = json_object_get_string(json_object_object_get(jsonObj_1, "username"));

    Json::Value root;
    Json::CharReaderBuilder reader;

    /* 解析json字符串 */
    std::istringstream s(info);

    Json::parseFromStream(reader, s, &root, nullptr);

    std::string username = root["username"].asString();
    std::string passwd = root["passwd"].asString();

    if (userExist(username))
    {
        std::cout << "用户名已存在！" << std::endl;
        return;
    }
    else
    {
        db->connect("./test.db");
        char sql[1024] = {0};
        sprintf(sql, "insert into COMPANY(username,passwd) values('%s','%s')", username.c_str(), passwd.c_str());
        std::cout << "recv login message : " << std::endl;
        if (db->execute(sql))
        {
            db->close();
        }
        else
        {
            db->close();
        }
    }
    /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(REGISTER));
    json_object_object_add(jsonObj, "status", json_object_new_string("ON_SUCCESS"));
    json_object_object_add(jsonObj, "reason", json_object_new_string("注册成功"));

    const char *jsonStr = json_object_to_json_string(jsonObj);

    std::cout << jsonStr << std::endl;
    m_clientSock->sendMessage(jsonStr);
    // std::cout << "账号注册成功！" << std::endl;
}

void WUziqiServer::handleLoginInfo(const std::string &info)
{
    json_object *jsonObj_1 = json_tokener_parse(info.c_str());
    // std::cout << info << std::endl;
    if (jsonObj_1 == NULL)
    {
        std::cout << "解析失败" << std::endl;
        return;
    }

    /* json字符串解析成功 */
    int type_1 = json_object_get_int(json_object_object_get(jsonObj_1, "type"));
    const char *username_1 = json_object_get_string(json_object_object_get(jsonObj_1, "username"));
    Json::Value root;
    Json::CharReaderBuilder reader;

    /* 解析json字符串 */
    std::istringstream s(info);

    Json::parseFromStream(reader, s, &root, nullptr);

    std::string username = root["username"].asString();
    std::string passwd = root["passwd"].asString();

   // m_map[username] = m_clientSock->getAttrConnfd();
    
    if (userExist(username) == false)
    {
        std::cout << "用户名不存在！" << std::endl;
         /* 创建一个json对象 */
        json_object *jsonObj = json_object_new_object();
        json_object_object_add(jsonObj, "type", json_object_new_int(LOGIN));
        json_object_object_add(jsonObj, "status", json_object_new_string("ON_FAIL"));
        json_object_object_add(jsonObj, "reason", json_object_new_string("用户不存在"));
        const char *jsonStr = json_object_to_json_string(jsonObj);

        std::cout << jsonStr << std::endl;
        m_clientSock->sendMessage(jsonStr);
        return;
    }
   
    /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(LOGIN));
    json_object_object_add(jsonObj, "status", json_object_new_string("ON_SUCCESS"));
    json_object_object_add(jsonObj, "reason", json_object_new_string("登录成功"));

    const char *jsonStr = json_object_to_json_string(jsonObj);

    std::cout << jsonStr << std::endl;
    m_clientSock->sendMessage(jsonStr);

    std::cout << m_queue.size() << std::endl;
   
}

void WUziqiServer::handleMatch(const std::string &info)
{
    m_queue.push(m_clientSock->getAttrConnfd());

    if(m_queue.size() < 2)
    {
        /* 创建一个json对象 */
        json_object *jsonObj = json_object_new_object();
        json_object_object_add(jsonObj, "type", json_object_new_int(MATCH));
        json_object_object_add(jsonObj, "status", json_object_new_string("ON_WAIT"));
        json_object_object_add(jsonObj, "reason", json_object_new_string("正在匹配..."));

        const char *jsonStr = json_object_to_json_string(jsonObj);

        std::cout << jsonStr << std::endl;
        m_clientSock->sendMessage(jsonStr);
    }
    else
    {
        int connfd = m_queue.front();
        
        std::cout << "connfd " <<connfd << std::endl;
        std::cout << "m_connfd " <<m_clientSock->getAttrConnfd() << std::endl;

        m_map[m_queue.front()] = m_clientSock->getAttrConnfd(); 
        m_queue.pop();
        std::cout << "fornt" <<m_queue.front() << std::endl;
        m_map[m_clientSock->getAttrConnfd()] = connfd;
        m_queue.pop();

        m_clientSock->setAttrConnfd(connfd);

          /* 创建一个json对象 */
        json_object *jsonObj1 = json_object_new_object();
        json_object_object_add(jsonObj1, "type", json_object_new_int(MATCH));
        json_object_object_add(jsonObj1, "status", json_object_new_string("ON_FULL"));
        json_object_object_add(jsonObj1, "reason", json_object_new_string("先手"));

        const char *jsonStr1 = json_object_to_json_string(jsonObj1);

       
        m_clientSock->sendMessage(jsonStr1);

        m_clientSock->setAttrConnfd( m_map[connfd]);

          /* 创建一个json对象 */
        json_object *jsonObj = json_object_new_object();
        json_object_object_add(jsonObj, "type", json_object_new_int(MATCH));
        json_object_object_add(jsonObj, "status", json_object_new_string("ON_FULL"));
        json_object_object_add(jsonObj, "reason", json_object_new_string("后手"));

        const char *jsonStr2 = json_object_to_json_string(jsonObj);
        
        m_clientSock->sendMessage(jsonStr2);
    }
}

void WUziqiServer::handlePlay(const std::string &info)
{
    int connfd = m_clientSock->getAttrConnfd();
    m_clientSock->setAttrConnfd(m_map[m_clientSock->getAttrConnfd()]);
    m_clientSock->sendMessage(info);
    m_clientSock->setAttrConnfd(connfd);

}

void WUziqiServer::handleBack(const std::string &info)
{
    std::cout << info << std::endl;
    int connfd = m_clientSock->getAttrConnfd();
    m_clientSock->setAttrConnfd(m_map[m_clientSock->getAttrConnfd()]);
    m_clientSock->sendMessage(info);
    m_clientSock->setAttrConnfd(connfd);
}

bool WUziqiServer::userExist(const std::string &username)
{
    db->connect("./test.db");
    const std::string sql = "select username from COMPANY where username = '" + username + "';";
    QueryResult result = db->query(sql);

    if (result.datas.size() == 0)
    {

        db->close();
        return false;
    }
    else
    {
        db->close();
        return true;
    }
}
